var express = require('express');
var router = express.Router();
var { UserModel, GoodModel, CartModel, RoleModel, AnnoModel, XuekeModel, ClassModel, AdviseModel } = require("../mongo/model")
var { FindOneDataFromTable, FindOneDataFromTableAsync, InsertDataFromTableAsync, UpdateDataFromTableAsync, FindAllDataFromTableAsync, RemoveDataFromTableAsync } = require('../mongo/index')
var { createToken, checkToken } = require('../utils/token')
var axios = require('axios');
// Vue3 项目的接口 
// 子路由 
// 路由地址 = /api/接口地址 

router.get('/test', (req, res) => {
    res.json({
        code: 200,
        msg: "测试 ---  Vue3 项目的接口  --- API - API - API ",
        result: {}
    })
})


// 添加  { username,phone,password }
router.post('/register', (req, res) => {
    var body = req.body;
    UserModel.findOne({
        $or: [    // 或者 $inc 
            {
                username: body.username,
            },
            {
                phone: body.phone
            }
        ]
    }).then(result => {
        if (result) {
            // 已经注册 
            res.json({
                code: 401,
                msg: '当前用户名或者手机已经被注册',
            })
        } else {
            body.time = new Date()
            UserModel.insertMany(body)
                .then(data => {
                    res.json({
                        code: 200,
                        msg: '注册成功',
                        result: data
                    })
                })
        }
    })
        .catch(err => {
            res.json({
                code: 500,
                msg: '服务器异常',
                err,
                result: {}
            })
        })
})


// 登录 
router.post('/login', (req, res) => {
    var body = req.body;
    UserModel.findOne({
        $or: [
            { username: body.account },  // account 可能是手机号也有可能是用户名 
            { phone: body.account },
        ]
    })
        .then(result => {
            if (result) {
                if (result.password == body.password) {

                    // 创造token 
                    var token = createToken({
                        username: result.username,
                        phone: result.phone,
                        password: result.password,
                    })

                    res.json({
                        code: 200,
                        msg: '登录成功',
                        result,
                        token: token
                    })
                } else {
                    res.json({
                        code: 401,
                        msg: '账号或者密码不匹配',
                        result: {}
                    })
                }
            } else {
                res.json({
                    code: 401,
                    msg: '账号不存在,请先去注册',
                    result: {}
                })
            }
        })
        .catch(err => {
            res.json({
                code: 500,
                msg: '服务器异常',
                err,
                result: {}
            })
        })
})


// 添加  { username,phone,password }
router.post('/adduser', (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        UserModel.findOne({
            $or: [    // 或者 $inc 
                {
                    username: body.username,
                },
                {
                    phone: body.phone
                }
            ]
        }).then(result => {
            if (result) {
                // 已经注册 
                res.json({
                    code: 401,
                    msg: '当前用户名或者手机已经被注册',
                })
            } else {
                body.time = new Date()
                UserModel.insertMany(body)
                    .then(data => {
                        res.json({
                            code: 200,
                            msg: '添加成功',
                            result: data
                        })
                    })
            }
        })
            .catch(err => {
                res.json({
                    code: 500,
                    msg: '服务器异常',
                    err,
                    result: {}
                })
            })
    })
})

// 判断手机号是否存在 
router.post("/chechphone", async (req, res) => {
    var body = req.body;

    // 3. 
    let result = await FindOneDataFromTableAsync({
        model: UserModel,
        res,
        query: {
            phone: body.phone,
        },
        next: 1  // 有下一步
    })
    if (result) {
        res.json({
            code: 200,
            msg: '手机号存在',
            flag: true,
            result
        })
    } else {
        res.json({
            code: 401,
            msg: '手机号尚未注册',
            flag: false
        })
    }

    // 2. 
    // FindOneDataFromTable({
    //   model: UserModel,
    //   res,
    //   query: {
    //     phone: body.phone,
    //   },
    //   next: (result) => {
    //     if (result) {
    //       res.json({
    //         code: 200,
    //         msg: '手机号存在',
    //         flag: true
    //       })
    //     } else {
    //       res.json({
    //         code: 401,
    //         msg: '手机号尚未注册',
    //         flag: false
    //       })
    //     }
    //   }
    // })

    // 1 

    //   UserModel.findOne({
    //       phone:body.phone,
    //   })
    //   .then(result=>{
    //      if(result){
    //       res.json({
    //         code:200,
    //         msg:'手机号已经注册',
    //         flag:true 
    //       })
    //      }else{
    //       res.json({
    //         code:401,
    //         msg:'手机号尚未注册',
    //         flag:false 
    //       })
    //     }
    //   })
    //   .catch(err=>{
    //     res.json({
    //       code:500,
    //       msg:'服务器异常',
    //       err,
    //       result:{}
    //     })
    //  })
})


router.post("/gettoken", (req, res) => {
    var data = req.body;    // 需要加密的数据 
    var token = createToken(data)
    res.json({
        code: 200,
        msg: '成功',
        token
    })
})


// 获取用户信息
router.post('/getuserinfo', (req, res) => {
    checkToken(req, res, ({ username, phone, password }) => {
        FindOneDataFromTableAsync({
            model: UserModel,
            res,
            query: {
                username
            }
        })
    })
})

// 修改密码 不要token 
router.post('/changepass', (req, res) => {
    var body = req.body;
    UpdateDataFromTableAsync({
        model: UserModel,
        res,
        query: {
            phone: body.phone,
        },
        data: {
            password: body.password
        }
    })
})




// 修改用户信息 复用 
router.post('/changeuserinfo', (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        UpdateDataFromTableAsync({
            model: UserModel,
            res,
            query: {
                username
            },
            data: body
        })
    })
})


// 上传文件 
const multer = require("multer");

const storage = multer.diskStorage({  // 存储对象   diskStorage 硬盘存储
    destination: function (req, file, cb) {   // 存储的目录 
        cb(null, 'public/upload')
    },
    filename: function (req, file, cb) {  // 存储的文件名 
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, "WH2214_" + uniqueSuffix + "_" + file.originalname)  // 1.jpg  避免命名冲突 
    }
})

const upload = multer({ storage: storage }).any()   // 接受任何类型格式的文件 

router.post("/uploadfile", upload, (req, res) => {
    checkToken(req, res, ({ username }) => {
        var file = req.files[0]
        res.json({
            code: 200,
            msg: '文件上传成功',
            file,
            path: file.path   // 上传文件 目的就是为了得到 文件在服务器的路径 
        })
    })
})


// 角色列表
router.post('/getrolelist', (req, res) => {
    var body = req.body;
    var keyword = body.keyword
    var query = {
        label: new RegExp(keyword)   // 模糊搜索 
    }
    checkToken(req, res, ({ username }) => {
        FindAllDataFromTableAsync({
            model: RoleModel,
            res,
            query
        })
    })
})


// 用户全部列表 
router.post('/getallusers', (req, res) => {
    var body = req.body;
    var username = body.username
    var phone = body.phone
    var role = body.role
    var query = {}
    if (username) {
        query.username = new RegExp(username)   // 模糊搜索 
    }
    if (phone) {
        query.phone = new RegExp(phone)   // 模糊搜索 
    }
    if (role) {
        query.role = role   // 模糊搜索 
    }
    checkToken(req, res, ({ username }) => {
        FindAllDataFromTableAsync({
            model: UserModel,
            res,
            query
        })
    })
})


// 删除权限 
router.post("/roledelete", (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        RemoveDataFromTableAsync({
            model: RoleModel,
            query: {
                _id: body._id
            },
            res   // 必传的 
        })
    })
})

// 添加权限 
router.post("/roleadd", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {

        let result = await FindOneDataFromTableAsync({
            model: RoleModel,
            res,
            query: {
                value: body.value
            },
            next: 1 // 下一步操作 
        })
        // 数组的值  All  []
        //  对象    One   null  
        // then 回调  
        if (result) {
            res.json({
                code: 401,
                msg: '当前权限已存在,请重新插入',
                result: result
            })
        } else {
            // 插入 
            InsertDataFromTableAsync({
                model: RoleModel,
                data: body,
                res   // 必传的 
            })
        }
    })
})


// 修改权限 
router.post("/roleupdate", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {

        let result = await FindOneDataFromTableAsync({
            model: RoleModel,
            res,
            query: {
                value: body.value,
                label: body.label,
            },
            next: 1
        })
        if (result) {
            res.json({
                code: 401,
                msg: '当前权限已存在,请重新修改',
                result: result
            })
        } else {
            // 修改
            UpdateDataFromTableAsync({
                model: RoleModel,
                query: {
                    _id: body._id,
                },
                data: body,
                res   // 必传的 
            })
        }
    })
})


// 添加公告
router.post("/annoadd", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        // 插入 
        body.time = new Date()
        InsertDataFromTableAsync({
            model: AnnoModel,
            data: body,
            res   // 必传的 
        })
    })
})

// 公告列表 
router.post('/getannolist', (req, res) => {
    var body = req.body;
    var keyword = body.keyword
    var type = body.type
    var query = {}  // 搜索
    if (keyword) {
        query.title = new RegExp(keyword)
    }
    if (type) {
        query.type = type;
    }


    checkToken(req, res, ({ username }) => {
        FindAllDataFromTableAsync({
            model: AnnoModel,
            res,
            query
        })
    })
})

// 公告删除 
router.post("/annodelete", (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        RemoveDataFromTableAsync({
            model: AnnoModel,
            query: {
                _id: body._id
            },
            res   // 必传的 
        })
    })
})

// 修改权限 
router.post("/annoupdate", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        // 修改
        UpdateDataFromTableAsync({
            model: AnnoModel,
            query: {
                _id: body._id,
            },
            data: body,
            res   // 必传的 
        })
    })
})

// 查询一条公告  
router.post("/getannodetail", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        // 修改
        FindOneDataFromTableAsync({
            model: AnnoModel,
            query: {
                _id: body._id,
            },
            res   // 必传的 
        })
    })
})


// 添加用户  { username,phone,password }
router.post('/adduser', (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        let result = await FindOneDataFromTableAsync({
            model: UserModel,
            query: {
                $or: [    // 或者 $inc 
                    {
                        username: body.username,
                    },
                    {
                        phone: body.phone
                    }
                ]
            },
            res,
            next: 1,
        })
        console.log(result)
        if (result) {
            // 已经注册 
            res.json({
                code: 401,
                msg: '当前用户名或者手机已经被注册',
            })
        } else {
            body.time = new Date()
            InsertDataFromTableAsync({
                model: UserModel,
                res,
                data: body,
                msg: '添加用户成功'
            })
        }
    })
})


// 用户列表 
router.post('/getuserlist', (req, res) => {
    var body = req.body;
    var keyword = body.keyword
    var role = body.role
    var date = body.date
    var query = {}  // 搜索
    var all = body.all // all true 查询所有不需要条件 
    body.pageNo = body.pageNo || 1; // 默认第一页 
    body.pageSize = body.pageSize || 5; // 默认5条 

    if (keyword) {
        query.username = new RegExp(keyword)
    }
    if (role) {
        query.role = role;
    }

    if (date) {
        // 区间搜索 
        query.time = {
            $gte: date[0],
            $lte: date[1]
        }
    }

    // 分页  
    // 查询出多少条数据  


    checkToken(req, res, async ({ username }) => {
        let result = await FindAllDataFromTableAsync({
            model: UserModel,
            res,
            next: 1,
            query,
        })

        let alldata = await FindAllDataFromTableAsync({
            model: UserModel,
            res,
            next: 1,
        })

        let data = await FindAllDataFromTableAsync({
            model: UserModel,
            res,
            query,
            skip: (body.pageNo - 1) * body.pageSize,
            limit: body.pageSize,
            next: 1
        })
        if (all) {
            res.json({
                code: 200,
                msg: '查询成功',
                result: alldata,
            })
        } else {
            res.json({
                code: 200,
                msg: '查询成功',
                result: data,
                total: result.length, // 总条数 
                pageSize: body.pageSize,
                pageNo: body.pageNo
            })
        }

    })
})


router.post("/deleteuser", (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        RemoveDataFromTableAsync({
            model: UserModel,
            query: {
                _id: body._id
            },
            res   // 必传的 
        })
    })
})

// 修改权限 
router.post("/updateuser", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        // 修改
        UpdateDataFromTableAsync({
            model: UserModel,
            query: {
                _id: body._id,
            },
            data: body,
            res   // 必传的 
        })
    })
})



// 添加学科
router.post('/addxueke', (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        let result = await FindOneDataFromTableAsync({
            model: XuekeModel,
            query: {
                value: body.value,  // 编码 
            },
            res,
            next: 1,
        })
        console.log(result)
        if (result) {
            res.json({
                code: 401,
                msg: '当前学科已经存在',
            })
        } else {
            body.time = new Date()
            InsertDataFromTableAsync({
                model: XuekeModel,
                res,
                data: body,
            })
        }
    })
})

router.post("/deletexueke", (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        RemoveDataFromTableAsync({
            model: XuekeModel,
            query: {
                _id: body._id
            },
            res   // 必传的 
        })
    })
})

// 
router.post("/updatexueke", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        // 修改
        UpdateDataFromTableAsync({
            model: XuekeModel,
            query: {
                _id: body._id,
            },
            data: body,
            res   // 必传的 
        })
    })
})

router.post('/getxuekelist', (req, res) => {
    var body = req.body;
    var keyword = body.keyword || body.label
    var value = body.value
    var query = {}  // 搜索
    if (keyword) {
        query.label = new RegExp(keyword)
    }
    if (value) {
        query.value = new RegExp(value);
    }


    checkToken(req, res, ({ username }) => {
        FindAllDataFromTableAsync({
            model: XuekeModel,
            res,
            query
        })
    })
})


// 添加班级 
router.post('/addclass', (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        let result = await FindOneDataFromTableAsync({
            model: ClassModel,
            query: {
                year: body.year,
                num: body.num,
                xueke: body.xueke,
            },
            res,
            next: 1,
        })
        console.log(result)
        if (result) {
            res.json({
                code: 401,
                msg: '当前班级已经存在',
            })
        } else {
            body.time = new Date()
            let xueke = await FindOneDataFromTableAsync({
                model: XuekeModel,
                query: {
                    value: body.xueke,
                },
                res,
                next: 1,
            })
            body.value = body.xueke + '-' + body.year.toString().slice(2, 4) + (body.num < 10 ? '0' + body.num : body.num);
            body.label = xueke.label + '-' + body.year.toString().slice(2, 4) + (body.num < 10 ? '0' + body.num : body.num);

            InsertDataFromTableAsync({
                model: ClassModel,
                res,
                data: body,
            })
        }
    })
})


router.post('/getclasslist', (req, res) => {
    var body = req.body;
    var xueke = body.xueke
    var year = body.year
    var num = body.num
    var keyword = body.keyword
    var query = {}  // 搜索

    if (keyword) {
        query.label = new RegExp(keyword)
    }
    if (xueke) {
        query.xueke = xueke;
    }
    if (year) {
        query.year = year;
    }
    if (num) {
        query.num = num;
    }


    checkToken(req, res, ({ username }) => {
        FindAllDataFromTableAsync({
            model: ClassModel,
            res,
            query
        })
    })
})



// 添加意见
router.post('/addadvise', (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {

        // username 通过 username 去把用户信息查询出来   
        body.time = new Date()
        InsertDataFromTableAsync({
            model: AdviseModel,
            res,
            data: body,
        })
    })
})

router.post('/deleteadvise', (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        body.time = new Date()
        RemoveDataFromTableAsync({
            model: AdviseModel,
            query: {
                _id: body._id
            },
            res   // 必传的 
        })
    })
})


router.post("/updateadvise", (req, res) => {
    var body = req.body;
    checkToken(req, res, async ({ username }) => {
        // 修改
        UpdateDataFromTableAsync({
            model: AdviseModel,
            query: {
                _id: body._id,
            },
            data: body,
            res   // 必传的 
        })
    })
})



router.post('/getadviselist', (req, res) => {
    var body = req.body;
    var keyword = body.keyword
    var type = body.type
    var query = {}  // 搜索
    if (keyword) {
        query.title = new RegExp(keyword)
    }
    if (type) {
        query.type = type;
    }


    checkToken(req, res, ({ username }) => {
        FindAllDataFromTableAsync({
            model: AdviseModel,
            res,
            query
        })
    })
})


router.post('/getadviseone', (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        FindOneDataFromTableAsync({
            model: AdviseModel,
            res,
            query: {
                _id: body._id
            }
        })
    })
})



// 

router.post("/sendcaptcha", async (req, res) => {
    const body = req.body;
    let result = await FindOneDataFromTableAsync({
        model: UserModel,
        next: 1,
        res,
        query: {
            phone: body.phone
        }
    })
    if (result) {
        // 发送验证码 
        axios.get('http://121.196.235.163:3000/captcha/sent', {
            params: {
                phone: body.phone
            }
        })
            .then(data => {
                console.log(data.data)
                res.json({
                    code: data.data.code,
                    msg: data.data.code == 200 ? '发送成功' : '发送失败',
                    result: data.data,
                })
            })
            .catch(err => {
                console.log(err)
                res.json({
                    code: 500,
                    msg: '发送失败,未知错误',
                    err,
                })
            })


    } else {
        //  
        res.json({
            code: 500,
            msg: '手机号未注册'
        })
    }
})


// 验证验证码
router.post("/verifycaptcha", async (req, res) => {
    const body = req.body;
    let result = await FindOneDataFromTableAsync({
        model: UserModel,
        next: 1,
        res,
        query: {
            phone: body.phone
        }
    })
    if (result) {
        // 发送验证码 
        axios.get('http://121.196.235.163:3000/captcha/verify', {
            params: body
        })
            .then(data => {
                console.log(data.data)
                if (data.data.code == 200) {
                    const token = createToken({
                        username: result.username,
                        phone: result.phone,
                        password: result.password
                    })
                    res.json({
                        code: data.data.code,
                        msg: '发送成功',
                        result: result,
                        data: data.data,
                        token
                    })
                } else {
                    res.json({
                        code: data.data.code,
                        msg: '发送失败',
                        result: data.data,
                    })
                }

            })
            .catch(err => {
                console.log(err)
                res.json({
                    code: 500,
                    msg: '验证失败,未知错误',
                    err,
                })
            })


    } else {
        //  
        res.json({
            code: 500,
            msg: '手机号未注册'
        })
    }
})
module.exports = router